package com.ls.pattern.proxy.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TransactionHandlerByJdk implements InvocationHandler {

    /**
     * 目标对象
     */
    private Object target;

    /**
     * 获取代理对象的方法
     *
     * @param target 目标对象
     * @return 代理对象
     */
    public Object getInstance(Object target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        before();

        Object invoke = null;
        try {
            invoke = method.invoke(this.target, args);
        } catch (Exception e) {
            afterThrowing();
        }

        after();

        return invoke;
    }

    private void before() {
        System.out.println("开启事务");
    }

    private void after() {
        System.out.println("提交事务");
    }

    private void afterThrowing() {
        System.out.println("回滚事务");
    }

}